import os.path
import sys

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

import click
from operator import itemgetter

from dp_analysis.analysis.base import DrawBase
from dp_analysis.db.connection import Mysql
from dp_analysis.utils.decorate import decorate


class DrawWordCloudV2(DrawBase):
    """
    对北京地区单个店铺的评论绘制词云
    """
    def __init__(self):
        super().__init__()

        self.save_path = "word_cloud/word_cloud_v2"

    @decorate(obj_name="DrawWordCloudV2")
    def analyse(self, db):
        with Mysql("dp", db) as mysql:
            connection = mysql.engine.connect()

            result_list = connection.execute(
                    "SELECT shop_id, COUNT( * ) FROM bj_shop_comment GROUP BY shop_id;").fetchall()
            result_list.sort(key=itemgetter(1), reverse=True)

        # 绘制评论数量前三的店铺词云
        for (shop_id, _) in result_list[:3]:
            # 评论词汇统计
            number, text_dict = 0, dict()
            for (comment,) in connection.execute(
                    f"SELECT comment FROM bj_shop_comment WHERE shop_id={shop_id!r}").fetchall():
                for word in self.participle(comment):
                    if word in self.stopwords_set:
                        continue
                    text_dict.setdefault(word, 0)
                    text_dict[word] += 1
                number += 1
                if number % 100 == 0:
                    print(f"已处理{number}条评论...")
            print(f"共处理评论{number}条！")
            if not number:
                print(f"{shop_id}评论数据加载有误！\n\n")
                continue
            text_list = list()
            for _str, _count in text_dict.items():
                text_list.extend([_str] * _count)

            file_name = f"店铺({shop_id})评论高频词云"
            # 绘制词云
            self.draw_word_cloud("北京", file_name, text_list, file_name, self.save_path)


@click.command()
@click.option("--db", default=0, help="请选择使用的数据库")
def main(db):
    draw_word_cloud_v2 = DrawWordCloudV2()
    draw_word_cloud_v2.analyse(int(db))


if __name__ == '__main__':
    main()
